package com.ctz.commonframe.ui.widget;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;

public abstract class AbsExpandableListAdapter<T, E> extends BaseExpandableListAdapter {
	protected Context context;
	protected List<T> groupList;
	protected LayoutInflater inflater;
	protected int groupLayoutId;
	protected int childLayoutId;

	public AbsExpandableListAdapter(Context context, List<T> groupList, int groupLayoutId, int childLayoutId) {
		this.context = context;
		this.groupList = groupList;
		this.groupLayoutId = groupLayoutId;
		this.childLayoutId = childLayoutId;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public E getChild(int groupPosition, int childPosition) {
		List<E> childList = getChildList(getGroup(groupPosition));
		return childList.get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		List<E> childList = getChildList(getGroup(groupPosition));
		if (childList == null)
			return 0;
		return childList.size();
	}

	@Override
	public T getGroup(int groupPosition) {
		return groupList.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		if(groupList == null)
			return 0;
		return groupList.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
		AdapterViewHolder holder = AdapterViewHolder.getInstance(context, convertView, parent, childLayoutId, childPosition);
		convertChild(holder, getChild(groupPosition, childPosition));
		return holder.getConvertView();
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		AdapterViewHolder holder = AdapterViewHolder.getInstance(context, convertView, parent, groupLayoutId, groupPosition);
		convertGroup(holder, getGroup(groupPosition), isExpanded, getChildrenCount(groupPosition));
		return holder.getConvertView();
	}

	public abstract List<E> getChildList(T t);
	
	public abstract void convertChild(AdapterViewHolder holder, E data);

	public abstract void convertGroup(AdapterViewHolder holder, T data, boolean isExpanded, int childCount);

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

}
